package thread.n8;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 带调度功能的线程池测试：
 */
public class TimerTest {
    public static void main(String[] args) {
        ScheduledExecutorService service = Executors.newScheduledThreadPool(2);
        //延迟执行。
        service.schedule(()->{
            System.out.println("task1");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },1, TimeUnit.SECONDS);

        service.schedule(()->{
            System.out.println("task2");
        },1, TimeUnit.SECONDS);

        //定时执行。从第一秒开始，每隔1s（从任务执行结束开始算的）执行一次。
        service.scheduleAtFixedRate(()->{
            System.out.println("task3");
        },1,1, TimeUnit.SECONDS);

    }


    //需求：如何让每周四 18:00:00 定时执行任务。
    private void test1(){
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);

        LocalDateTime now = LocalDateTime.now();
        //这是当前周的周四。
        LocalDateTime with = now.withHour(18).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.THURSDAY);
        //如果当前时间 > 本周时间，必须找到下一周的周四。
        if(with.isBefore(now)){
            with = with.plusWeeks(1);
        }
        //initialDelay：当前时间和目标时间的时间差。
        //period：这次执行的时间和下次执行的时间的周期。
        long initialDelay = Duration.between(now,with).toMillis();
        long period = 1000 * 60 * 60 * 24 * 7;

        pool.scheduleAtFixedRate(()->{
            System.out.println("running...");
        },initialDelay,period,TimeUnit.MILLISECONDS);

    }

}
